package com.cn.xiongmeng.czlxz.ui;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.cn.xiongmeng.czlxz.R;
import com.cn.xiongmeng.czlxz.activity.IndexActivity;
import com.cn.xiongmeng.czlxz.network.HttpClient;
import com.cn.xiongmeng.czlxz.utils.IntervalControler;

import org.json.JSONException;
import org.json.JSONObject;

public class TlFragment extends Fragment implements View.OnClickListener {

    private static final String TAG = "TlFragment";
    IndexActivity activity;
    private HttpClient httpClient;
    //private ProgressBar progressBar;
    public TlFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Log.d(TAG, "onAttach");
        // 获取Activity实例
        activity = (IndexActivity) context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_tl, container, false);

        // progressBar = rootView.findViewById(R.id.progressBar);
        httpClient = new HttpClient(getContext());

        ImageView btnOff = rootView.findViewById(R.id.btn_off);
        ImageView btnHuoqu = rootView.findViewById(R.id.img_huoqu);

        btnOff.setOnClickListener(this);
        btnHuoqu.setOnClickListener(this);

        return rootView;
    }

    @Override
    public void onClick(View v){
        if (v.getId() == R.id.btn_off){
            Log.d(TAG, "点击叉号");

            FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            // 隐藏Fragment
            if (this.isAdded()) {
                fragmentTransaction.hide(this);
            }
            fragmentTransaction.commit();
        } else if (v.getId() == R.id.img_huoqu) {
            Log.d(TAG, "点击免费获取");

            Context context = activity; //
            Runnable controlledFunc = () -> {
                // 这里是需要控制调用间隔的函数
                // System.out.println("Function called");
                // Log.d(TAG, "Function called");
                freeObtain();
            };

            IntervalControler.intervalControlForObtainingTl(context, controlledFunc, "preHuoquTime", 10);
        }
    }
    private void freeObtain(){
        SharedPreferences prefs = getActivity().getSharedPreferences("AppPrefs", Context.MODE_PRIVATE);
        String fakeUser = prefs.getString("fakeUser", "");

        if (fakeUser.length() != 0){
            try {
                JSONObject jsonObject = new JSONObject(fakeUser);
                String fakeUid = jsonObject.getString("fake_uid");

                JSONObject jsonObject2 = new JSONObject();
                jsonObject2.put("fakeUid", fakeUid);
                String jsonString = jsonObject2.toString();
                String url = "https://little-moon.fun/obtain_one_tl/";

                httpClient.sendPostRequest(url, jsonString, new HttpClient.Callback() {
                    @Override
                    public void onFailure(Exception e) {
                        // （测试没问题）
                        activity.runOnUiThread(() -> {
                            // Log.e(TAG, "Post 请求失败", e); // Log 错误信息
                            Toast.makeText(activity, "请稍后再试！", Toast.LENGTH_LONG).show();
                        });
                    }

                    @Override
                    public void onResponse(String response) {
                        activity.runOnUiThread(() -> {
                            // Log.d(TAG, "Post 请求成功: " + response); // Log 成功响应
                            // 1、提示
                            Toast.makeText(activity, "体力 + 1", Toast.LENGTH_LONG).show();
                            // 2、修改数值
                            String _totalTl = activity.tvTotalTl.getText().toString();
                            String totalTl = String.valueOf(Integer.parseInt(_totalTl) + 1);
                            activity.tvTotalTl.setText(totalTl);
                            // 3、更新缓存
                            try{
                                jsonObject.put("total_tl", totalTl);
                                SharedPreferences.Editor editor = prefs.edit();

                                editor.putString("fakeUser", jsonObject.toString());
                                editor.apply(); // apply异步，commit同步
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        });
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            // （测试没问题）
            activity.runOnUiThread(() -> {
                Toast.makeText(activity, "请稍后再试！", Toast.LENGTH_LONG).show();
            });
        }
    }
}